<template>
  <div class="login-container">
    <div class="login-box">
      <div class="login-header">
        <h2>书籍分享平台-用户</h2>
        <div class="tab-group">
          <div 
            class="tab-item" 
            :class="{ active: currentTab === 'login' }"
            @click="currentTab = 'login'"
          >
            登录
          </div>
          <div 
            class="tab-item" 
            :class="{ active: currentTab === 'register' }"
            @click="currentTab = 'register'"
          >
            注册
          </div>
        </div>
      </div>

      <!-- 登录表单 -->
      <el-form
        v-if="currentTab === 'login'"
        ref="loginFormRef"
        :model="loginForm"
        :rules="loginRules"
        class="login-form"
        size="large"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="loginForm.username"
            placeholder="用户名"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="loginForm.password"
            type="password"
            placeholder="密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <div class="form-actions">
          <el-checkbox v-model="rememberMe">记住我</el-checkbox>
        </div>
        <div class="button-group">
          <el-button 
            type="primary" 
            class="submit-btn" 
            @click="handleLogin"
          >
            登录
          </el-button>
        </div>
        <div class="skip-login">
          <el-button 
            type="text" 
            @click="skipLogin"
          >
            不想登录，先随便看看>>
          </el-button>
        </div>
      </el-form>

      <!-- 注册表单 -->
      <el-form
        v-if="currentTab === 'register'"
        ref="registerFormRef"
        :model="registerForm"
        :rules="registerRules"
        class="register-form"
        size="large"
      >
        <el-form-item prop="username">
          <el-input 
            v-model="registerForm.username"
            placeholder="用户名 (3-10位字母或数字)"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="nickname">
          <el-input 
            v-model="registerForm.nickname"
            placeholder="昵称 (2-6个字符)"
            :prefix-icon="User"
          />
        </el-form-item>
        <el-form-item prop="password">
          <el-input 
            v-model="registerForm.password"
            type="password"
            placeholder="密码 (6-10位字母或数字)"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <el-form-item prop="confirmPassword">
          <el-input 
            v-model="registerForm.confirmPassword"
            type="password"
            placeholder="确认密码"
            :prefix-icon="Lock"
            show-password
          />
        </el-form-item>
        <div class="button-group">
          <el-button 
            type="primary" 
            class="submit-btn" 
            @click="handleRegister"
          >
            注册
          </el-button>
        </div>
      </el-form>
    </div>
  </div>
</template>

<script setup>
import { ref, reactive } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/stores/user'
import { User, Lock } from '@element-plus/icons-vue'
import { login, register } from '@/api/user'

const router = useRouter()
const userStore = useUserStore()
const currentTab = ref('login')
const rememberMe = ref(false)

// 登录表单
const loginFormRef = ref(null)
const loginForm = reactive({
  username: '',
  password: ''
})

const loginRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{3,10}$/, message: '用户名只能包含3-10位字母或数字', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{6,10}$/, message: '密码只能包含6-10位字母或数字', trigger: 'blur' }
  ]
}

// 注册表单
const registerFormRef = ref(null)
const registerForm = reactive({
  username: '',
  nickname: '',
  password: '',
  confirmPassword: ''
})

const registerRules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{3,10}$/, message: '用户名只能包含3-10位字母或数字', trigger: 'blur' }
  ],
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { pattern: /^[\u4e00-\u9fa5a-zA-Z]{2,6}$/, message: '昵称长度在2到6个字符之间', trigger: 'blur' }
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { pattern: /^[a-zA-Z0-9]{6,10}$/, message: '密码只能包含6-10位字母或数字', trigger: 'blur' }
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    {
      validator: (rule, value, callback) => {
        if (value !== registerForm.password) {
          callback(new Error('两次输入的密码不一致'))
        } else {
          callback()
        }
      },
      trigger: 'blur'
    }
  ]
}

// 登录处理
const handleLogin = async () => {
  try {
    const valid = await loginFormRef.value.validate()
      .catch(err => {
        ElMessage.warning('请填写完整的登录信息')
        return false
      })
    
    if (!valid) return

    const response = await login({
      username: loginForm.username,
      password: loginForm.password,
      remember: rememberMe.value
    })
    
    if (response.code === 200) {
      // 检查用户状态
      if (response.data.user.status === 0) {
        ElMessage.error('该账号已被冻结')
        return
      }
      
      const { token, user } = response.data
      userStore.setToken(token)
      userStore.setUserInfo(user)
      ElMessage.success('登录成功')
      router.push('/user/home')
    } else {
      ElMessage.error(response.message || '登录失败')
    }
  } catch (error) {
    console.error('Login error:', error)
    ElMessage.error(error.response?.data?.message || '登录失败')
  }
}

// 注册处理
const handleRegister = async () => {
  try {
    // 先进行表单验证
    const valid = await registerFormRef.value.validate()
      .catch(err => {
        // 表单验证失败，显示警告信息
        ElMessage.warning('请填写完整的表单内容')
        return false
      })
    
    // 如果表单验证失败，直接返回
    if (!valid) return

    // 表单验证通过，发送注册请求
    const response = await register({
      username: registerForm.username,
      password: registerForm.password,
      nickname: registerForm.nickname
    })
    
    if (response.code === 200) {
      ElMessage.success('注册成功，请登录')
      currentTab.value = 'login'
      loginForm.username = registerForm.username
    } else {
      ElMessage.error(response.message || '注册失败')
    }
  } catch (error) {
    console.error('Register error:', error)
    ElMessage.error(error.response?.data?.message || '注册失败')
  }
}

// 跳转方法
const skipLogin = () => {
  router.push('/user/home')
}
</script>

<style scoped>
.login-container {
  min-height: 100vh;
  display: flex;
  justify-content: center;
  align-items: center;
  background-color: #f5f7fa;
}

.login-box {
  width: 400px;
  background: white;
  border-radius: 16px;
  box-shadow: 0 8px 32px rgba(0, 0, 0, 0.08);
  padding: 35px 40px;
}

.login-header {
  text-align: center;
  margin-bottom: 35px;
}

.login-header h2 {
  color: #409EFF;
  margin-bottom: 25px;
  font-size: 24px;
  font-weight: 600;
}

.tab-group {
  display: flex;
  justify-content: center;
  gap: 60px;
  margin-bottom: 35px;
  position: relative;
}

.tab-item {
  padding: 8px 4px;
  cursor: pointer;
  color: #909399;
  transition: all 0.3s;
  font-size: 16px;
  position: relative;
}

.tab-item::after {
  content: '';
  position: absolute;
  bottom: -2px;
  left: 50%;
  width: 0;
  height: 2px;
  background-color: #409EFF;
  transition: all 0.3s;
  transform: translateX(-50%);
}

.tab-item.active {
  color: #409EFF;
  font-weight: 500;
}

.tab-item.active::after {
  width: 100%;
}

:deep(.el-form-item) {
  margin-bottom: 25px;
  width: 280px;
  margin-left: auto;
  margin-right: auto;
}

:deep(.el-input__wrapper) {
  padding: 1px 15px;
  height: 42px;
}

:deep(.el-input__wrapper:hover) {
  box-shadow: 0 0 0 1px #c0c4cc;
}

:deep(.el-input__wrapper.is-focus) {
  box-shadow: 0 0 0 1px #409EFF;
}

.form-actions {
  width: 280px;
  margin: 0 auto 25px;
}

.button-group {
  display: flex;
  justify-content: center;
  margin-bottom: 20px;
}

.submit-btn {
  width: 180px;
  height: 42px;
  font-size: 16px;
  font-weight: 500;
  border-radius: 21px;
}

.skip-login {
  text-align: center;
  margin-top: -10px;
}

:deep(.skip-login .el-button--text) {
  color: #909399;
  font-size: 14px;
}

:deep(.skip-login .el-button--text:hover) {
  color: #409EFF;
}
</style> 